<template>
  <div class="dictation-section">
    <h2 class="section-title">听写区域</h2>
    <div class="mode-toggle">
      <div 
        class="mode-btn" 
        :class="{ active: currentMode === 'dictation' }"
        @click="switchMode('dictation')"
      >
        听写模式
      </div>
      <div 
        class="mode-btn" 
        :class="{ active: currentMode === 'repeat' }"
        @click="switchMode('repeat')"
      >
        跟读模式
      </div>
    </div>
    <div class="word-display">
      <div class="word" id="currentWord">{{ currentWord }}</div>
      <div class="meaning" id="currentMeaning">{{ showMeaning ? currentMeaning : '...' }}</div>
    </div>
    <div class="controls">
      <button class="btn control-btn" @click="prevWord" title="上一个">⬅️</button>
      <button 
        class="btn control-btn" 
        :class="isPlaying ? 'btn-warning' : 'btn-success'"
        @click="togglePlayPause" 
        :title="isPlaying ? '暂停' : '播放'"
      >
        {{ isPlaying ? '⏸️' : '▶️' }}
      </button>
      <button class="btn control-btn btn-danger" @click="stopWord" title="停止">⏹️</button>
      <button class="btn control-btn" @click="nextWord" title="下一个">➡️</button>
    </div>
    <div class="progress-container">
      <div class="progress-bar" :style="{ width: progressPercentage + '%' }"></div>
    </div>
    <div class="progress-text">{{ progress?.current }} / {{ progress?.total }}</div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { useDictationStore } from '../composables/useDictation'
import { useFrontendTTS } from '../composables/useFrontendTTS'

const dictationStore = useDictationStore()

// 使用计算属性确保响应性
const currentWord = computed(() => dictationStore.currentWord)
const currentMeaning = computed(() => dictationStore.currentMeaning)
const isPlaying = computed(() => dictationStore.isPlaying)
const currentMode = computed(() => dictationStore.currentMode)
const progress = computed(() => dictationStore.progress)
const showMeaning = computed(() => dictationStore.showMeaning)
const words = computed(() => dictationStore.words)

// 使用前端TTS组件
const { speak, stop: stopSpeaking, isSpeaking } = useFrontendTTS()

const progressPercentage = computed(() => {
  if (!progress.value || progress.value.total === 0) return 0
  return (progress.value.current / progress.value.total) * 100
})

const switchMode = (mode: string) => {
  dictationStore.setMode(mode)
}

const togglePlayPause = () => {
  if (isPlaying.value) {
    stopWord()
  } else {
    playWord()
  }
}

const playWord = async () => {
  if (dictationStore.words?.length === 0) {
    console.warn('词汇列表为空，无法播放')
    alert('请先加载词库！')
    return
  }
  
  // 使用前端TTS功能
  console.log('尝试播放单词:', currentWord.value)
  try {
    await speak(currentWord.value)
    dictationStore.setPlaying(true)
    
    // 如果启用了自动播放下一个，并且不是最后一个单词，则在播放完成后自动播放下一个
    if (dictationStore.config.autoPlay && progress.value.current < progress.value.total) {
      // 等待播放间隔后再播放下一个单词
      setTimeout(async () => {
        if (dictationStore.isPlaying) {
          await nextWord()
        }
      }, dictationStore.config.interval * 1000)
    }
  } catch (error) {
    console.error('播放单词失败:', error)
    alert('播放单词失败: ' + error)
  }
}

const stopWord = () => {
  // 停止TTS播放
  stopSpeaking()
  dictationStore.setPlaying(false)
}

const prevWord = async () => {
  try {
    await dictationStore.prevWord()
    // 如果之前正在播放，则继续播放新单词
    if (isPlaying.value) {
      stopWord()
      await playWord()
    }
  } catch (error) {
    console.error('切换到上一个单词失败:', error)
    alert('切换到上一个单词失败: ' + error)
  }
}

const nextWord = async () => {
  try {
    await dictationStore.nextWord()
    // 如果之前正在播放，则继续播放新单词
    if (isPlaying.value) {
      stopWord()
      await playWord()
    }
  } catch (error) {
    console.error('切换到下一个单词失败:', error)
    alert('切换到下一个单词失败: ' + error)
  }
}

// 处理播放第一个单词的事件
const handlePlayFirstWord = async () => {
  // 等待一小段时间确保状态更新完成
  await new Promise(resolve => setTimeout(resolve, 100))
  await playWord()
}

// 组件挂载时添加事件监听器
onMounted(() => {
  window.addEventListener('playFirstWord', handlePlayFirstWord)
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('playFirstWord', handlePlayFirstWord)
})
</script>

<style scoped>
/* 确保emoji在按钮中正确显示 */
.control-btn {
  font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Android Emoji", EmojiSymbols, sans-serif;
}
</style>